/**
 * Created by xiaox on 2017/7/4.
 */


var Lnglat = require('./model/Lnglat');
var Tile = require('./model/Tile');
var CoordinateUtil = require('./util/CoordinateUtil');

var fs = require('fs');
var http = require('http');
var path = require('path');

var downloadDir = '/Users/xiaox/xindong/googlemaps/roadmap/';

//load();

test();

var leftTopLnglat,rightBottomLnglat;

var util;

function load() {


    var zoom = [1, 2, 3, 4, 5, 6, 7];

    var mapExtent = '105.812987,30.334954,107.827147,28.613459';

    var extent = mapExtent.split(',');

    util = new CoordinateUtil();


    leftTopLnglat = new Lnglat(extent[0], extent[1]);

    rightBottomLnglat = new Lnglat(extent[2], extent[3]);

    console.log(leftTopLnglat.toString());

    calculatSize(zoom, leftTopLnglat, rightBottomLnglat);

    startDownload(zoom, leftTopLnglat, rightBottomLnglat);

}

function calculatSize(zoom, leftTopLnglat, rightBottomLnglat) {

    var size = 0;

    var util = new CoordinateUtil();

    for (var i = 0; i < zoom.length; i++) {

        var leftTopTile = util.lnglatToTile(zoom[i], leftTopLnglat.getLng(),leftTopLnglat.getLat());

        var rightBottomTile = util.lnglatToTile(zoom[i], rightBottomLnglat.getLng(),rightBottomLnglat.getLat());

        console.log(i);
        console.log(leftTopTile.getX());
        console.log(leftTopTile.getY());
        console.log(rightBottomTile.getX());
        console.log(rightBottomTile.getY());

        size += (rightBottomTile.getX() - leftTopTile.getX() + 1) * (rightBottomTile.getY() - leftTopTile.getY() + 1);

        size = parseInt(size);

        console.log(size);

        console.log("------------")
    }

    console.log("下载tile数量:" + size);
    console.log("下载大小:" + size * 22 + "k, " + parseInt(size * 22 / 1024) + "M, " + parseInt(size * 22 / 1024 / 1024) + "G");

    console.log("下载开始:--------------------------------------------------");
}

function startDownload(zoom, leftTopLnglat, rightBottomLnglat) {

    for(var i=0;i< zoom.length;i++){

        var leftTopTile = util.lnglatToTile(zoom[i], leftTopLnglat.getLng(),leftTopLnglat.getLat());

        var rightBottomTile = util.lnglatToTile(zoom[i], rightBottomLnglat.getLng(),rightBottomLnglat.getLat());

        //
        for(var x = leftTopTile.getX();x <= rightBottomTile.getX(); x++){
            for(var y = leftTopTile.getY();y <= rightBottomTile.getY(); y++){

                var tile = new Tile(x, y, zoom[i]);
                downloadXYZ(tile);
            }
        }
    }
}

function downloadXYZ(tile){


    var url="http://www.google.cn/maps/vt/pb=!1m5!1m4!1i"+tile.getZ()+"!2i"+tile.getX()+"!3i"+tile.getY()+"!4i128!2m2!1e0!3i383077076!3m7!2szh-CN!3scn!5e1105!12m1!1e47!12m1!1e3!4e0!5m2!1e0!5f2";

    var storePath = downloadDir + "/tiles/" + tile.getZ() + "/" + tile.getX() + "/" ;

    storePath = storePath.replace('//','/');

    var filePath = storePath + tile.getY() + ".png";

    var isOveride = true;

    if(fs.existsSync(storePath)){
        if(!isOveride){
            console.log("已缓存不下载:" + url);
        }
    }else{
        /**
         * Error: ENOENT: no such file or directory
         * 路径要一层一层建立
         *
         * 自定义遍历方法mkdirsSync
         */
        console.log("建立文件夹目录");
        mkdirsSync(storePath);
    }

    console.log(url);

    console.log(filePath);

    http.get(url,function(res){

        var strutsCode = res.statusCode;

        if(strutsCode!=200){
            console.log(url + "错误,代码 "+strutsCode);
            return false;
        }

        var img = res;

        // 管道 http中请求流 fs模块创建一个写入流 ，下载在 xxx目录下的xxx文件 ，文件夹名称以及图片格式，你可以 正则匹配/.xxx/

        img.pipe(fs.createWriteStream(filePath))
            .on('error',function(err){
                console.log(err);
            });


    }).on('error',function (err) {
        console.log(err.message);
    });

}

//递归创建目录 同步方法
function mkdirsSync(dirname) {
    //console.log(dirname);
    if (fs.existsSync(dirname)) {
        return true;
    } else {
        if (mkdirsSync(path.dirname(dirname))) {
            fs.mkdirSync(dirname);
            return true;
        }
    }
}

function test(){

    /**

     防止请求过于频繁导致ip被网站屏蔽，请求都是使用代理IP进行。所以必须先获取对可用的代理IP

     http://www.xicidaili.com/nn/

     获取回来的IP并不是每一个都可用，故需使用代理去请求http://ip.chinaz.com/getip.aspx ，若3秒内有响应即当作可用。具体代码如下：

     **/

    var gMapUrl = "http://mt2.google.cn/vt/lyrs=m&hl=zh-CN&gl=cn&x=420&y=193&z=9";

    var opts = {
        host:'110.73.5.181',
        port: 8123,
        method:'CONNECT',   //这里是发送的方法
        path:gMapUrl        //这里是访问的路径
    }

    var options = {
        host: 'mt2.google.cn',
        port: 80, //端口号 https默认端口 443， http默认的端口号是80
        path: gMapUrl,
        method: 'POST',
        Cookie:'NID=105=T4-vnpuZOoxoojS7HsWpRkkrIXkpof-M2hf6cUsu5mhk77FHHdmZcXWNpNqceI3PMzP4-wEzyNQQOUYDaGQEZYB6S2YFL0BIzUqZ9Meyw67GrcdjGGOJisfBSYf22koh',
        headers: {
            "Connection": "keep-alive",
            "Content-Length": 23390,
            "Content-Type": "image/png",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"
        }//伪造请求头
    };


    //var gMapUrl = "http://shangetu1.map.bdimg.com/it/u=x=6322;y=2359;z=15;v=009;type=sate&fm=46&app=webearth2&v=009&udt=20170704";
    //var gMapUrl = "http://www.google.cn/maps/vt/pb=!1m5!1m4!1i2!2i7!3i3!4i128!2m2!1e1!3i729!3m9!2szh-CN!3scn!5e1105!12m1!1e4!12m1!1e47!12m1!1e3!4e0!5m2!1e0!5f2";

    console.log(gMapUrl);

    http.request(options, function(res) {

        var strutsCode = res.statusCode;

        console.log(strutsCode);

        if(strutsCode!=200){
            console.log(gMapUrl + "下载错误,代码 "+strutsCode);
            return false;
        }


        var img = res;

        //img.pipe

    }).on('error', function(e) {
        console.log("get error: " + e.message);
    })

}